// pages/welcome/welcome.js
var util = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    pages:''
  },
  onLoad: function (option) {
   
    if (option.pages){
      var p = option.pages
      p = p.replace('$', '?').replace(/%/g, '=');
      this.setData({ pages: p });
    }
    
  },

  /**
   * 用户授权登录
   */
  userAuthorization: function (options) {
    var _this = this;
    console.log(options);
    if (options.detail.errMsg == 'getUserInfo:fail auth deny') {
      wx.showToast({ title: "为了您能正常使用小程序，请先同意授权", icon: "none" });
      return;
    }
    var userInfo = options.detail.userInfo
    wx.setStorage({
      key: "userInfo",
      data: userInfo
    });

    //首先登录用户
    wx.login({
      success: function (res) {
        //在服务器保存code和用户信息
        wx.request({
          url: getApp().baseUrl + '/wxapi/user/login/' + res.code,
          method: "POST",
          header: {
            'content-type': 'application/json'
          },
          data: {},
          success: function (res) {

            if (res.data.status == "200") {
              try {

                //保存用户token
                wx.setStorage({
                  key: "token",
                  data: res.data.mapInfo.token
                });
                var toPage = '../index/index'
                if (_this.data.pages){
                  toPage = _this.data.pages
                }
                console.log('toPage:'+toPage);
                //更新用戶信息
                util.request("/wxapi/user/saveUserInfo", userInfo, function (data) {
                  //跳转页面
                  console.log(data);
                  wx.reLaunch({
                    url: toPage
                  })
                }, false);
              } catch (e) {
                console.error(e);
                wx.hideLoading()
              }
            } else {
              wx.showToast({ title: res.data.info, icon: "none" });
              wx.hideLoading()
            }
            wx.hideLoading()
          },
          //失败处理
          fail: function (res) {
            wx.showToast({ title: "网络请求异常", icon: "none" });
          }
        })
      }
    });

  }
})